package com.services;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.springframework.stereotype.Service;

@Service
public class FileService {

  private final UrlValidator urlValidator = new UrlValidator();

  public File createTempFile(String prefix, String sufix) throws IOException {
    //TODO implement cache for files
    return File.createTempFile(prefix, sufix);
  }

  public File getFileFromUrl(String url) throws IOException {
    //TODO implement cache for files
    File file = createTempFile("tempFile", "");
    URL urlPath = new URL(url);
    FileUtils.copyURLToFile(urlPath, file);
    file.deleteOnExit();

    return file;
  }

  public String getFilePath(String input) throws IOException {
    String filename = input;

    if (urlValidator.isValid(input)) {
      filename = getFileFromUrl(input).getName();
    }

    String localFilePath = "file:///tmp/" + filename;

    return localFilePath;
  }

  public File getFileFromStorage(String filename) throws FileNotFoundException {
    File file = new File("/tmp/" + filename);

    if (!file.exists()) {
      throw new FileNotFoundException("File not found.");
    }

    return file;
  }

}
